package com.pro_one.mobile.controller;

import com.alibaba.fastjson.JSON;
import com.pro_one.constant.MessageConstant;
import com.pro_one.constant.RedisConstant;
import com.pro_one.entity.Result;
import com.pro_one.pojo.Member;
import com.pro_one.service.MemberService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping("/member")
public class MemberController {
    @Reference
    private MemberService memberService;
    @Autowired
    private JedisPool jedisPool;

    /**
     * 会员登录
     *
     * @param response
     * @param map
     * @return
     */
    @RequestMapping("/login")
    public Result login(HttpServletResponse response, @RequestBody Map map) {
        String validateCode = (String) map.get("validateCode");
        String telephone = (String) map.get("telephone");
        String validateCodeInRedis = jedisPool.getResource().get(telephone + RedisConstant.SENDTYPE_LOGIN);
        if (validateCodeInRedis == null || !validateCode.equals(validateCodeInRedis)) {
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
        Member member = memberService.findByTelephone(telephone);
        if (member == null) {
            member = new Member();
            member.setRegTime(new Date());
            member.setPhoneNumber(telephone);
            memberService.add(member);
        }
        Cookie cookie = new Cookie("login_member_telephone", telephone);
        cookie.setMaxAge(30 * 60 * 60);
        cookie.setPath("/");
        response.addCookie(cookie);
        String member4Json = JSON.toJSON(member).toString();
        jedisPool.getResource().setex(telephone, 60 * 30, member4Json);
        return new Result(true, MessageConstant.LOGIN_SUCCESS);
    }
}
